package util.thread.callable;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * @author root
 */
public class CallableTest {

    private static final Logger logger = LoggerFactory.getLogger(CallableTest.class);

    /**
     * Callable 的使用场景：加入子线程中有错误抛出、或者拿到线程执行的结果
     *
     * @param args args
     */
    public static void main(String[] args) {
        Callable<Object> callable = new DoOneCallable();
        FutureTask<Object> futureTask = new FutureTask<>(callable);
        try {
            // run 方法启动线程
            futureTask.run();
            // get() 获得当前线程的执行结果
            futureTask.get();
        } catch (Exception e) {
            logger.error("Error occur:{}", e.getMessage());
        }
        logger.info("hello!");
    }

    /**
     * callable 可以拿到线程中的异常
     */
    @Test
    public void test() {
        Callable<Object> callable = new DoOneCallable();
        try {
            callable.call();
        } catch (Exception e) {
            logger.error("Error occur:{}", e.getMessage());
        }
    }
}
